package com.yourname.xhs.dao;

import com.yourname.xhs.bean.Category;
import com.yourname.xhs.bean.Note;
import com.yourname.xhs.entity.User;
import com.yourname.xhs.util.DES;
import com.yourname.xhs.util.DbUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class NoteDaoImpl implements NoteDao{
    ResultSet rs=null;
    Connection conn=null;
    PreparedStatement ps= null;


    //创建笔记
    public boolean createNote(Note note,User user,String categoryName) throws SQLException {
        boolean i;
        try {
            conn=DbUtil.getConnection();

            String sql="insert into notes (title,content,category,user_nickname) values (?,?,?,?)";
            ps=conn.prepareStatement(sql);
            ps.setString(1,note.getTitle());
            ps.setString(2,note.getContent());
            ps.setString(3,categoryName);
            ps.setString(4,user.getUserName());
            int line=ps.executeUpdate();
            if(line>0){
                i=true;
            }
            else {
                i=false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            DbUtil.close(rs,ps,conn);
        }

        return i;
    }




    //删除笔记(管理员删除，可以删除所有人的笔记，看到所有id，不用担心删错了别人的id)
    public int deleteNoteById(Long id){
        int line=0;
      try{
          conn = DbUtil.getConnection();
          String sql = "delete from notes where id = ?";
          ps=conn.prepareStatement(sql);
          ps.setLong(1,id);
          line=ps.executeUpdate();
      }catch (Exception e){
          e.printStackTrace();
          throw  new RuntimeException(e);
      }finally {
          DbUtil.close(rs,ps,conn);
      }
         return line;
    }


    //删除笔记（个人）
    public int deletePersonalNoteById(Long id,User user){
        int line=0;
        try{
            conn = DbUtil.getConnection();
            String sql = "delete from notes where id = ? and user_nickname=? ";

            ps=conn.prepareStatement(sql);
            ps.setLong(1,id);
            ps.setString(2,user.getUserName());
            line=ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
            throw  new RuntimeException(e);
        }finally {
            DbUtil.close(rs,ps,conn);
        }
        return line;
    }








   //修改笔记(分标题和内容和发布区域)？？？？痛苦面具


    // 更新title
    public int updateTitle(Long id,User user, String newTitle)  {
        int rowsAffected;
         try {
             conn = DbUtil.getConnection();
             String sql = "UPDATE notes SET title = ? WHERE id = ? and user_nickname=?";
             ps = conn.prepareStatement(sql);

             ps.setString(1, newTitle);
             ps.setLong(2, id);
             ps.setString(3, user.getUserName());
              rowsAffected = ps.executeUpdate();

         }catch (Exception e){
             e.printStackTrace();
             throw  new RuntimeException(e);
         }
         finally{
             DbUtil.close(rs,ps,conn);
         }
         return rowsAffected;
    }

    // 更新content
    public int updateContent(Long id,User user, String newContent)  {
        int rowsAffected;
       try {
           conn = ps.getConnection();
           String sql = "UPDATE notes SET content = ? WHERE id = ?and user_nickname=?";
           ps = conn.prepareStatement(sql);

           ps.setString(1, newContent);
           ps.setLong(2, id);
           ps.setString(3, user.getUserName());
            rowsAffected = ps.executeUpdate();

       }catch (Exception e){
           e.printStackTrace();
           throw  new RuntimeException(e);
       }finally {
           DbUtil.close(rs,ps,conn);
       }
       return rowsAffected;
    }

    // 更新category
    public int updateCategory(Long id,User user, String newCategory)  {
        int rowsAffected;
        try {
            conn = DbUtil.getConnection();
            String sql = "UPDATE notes SET category = ? WHERE id =? and user_nickname=?";
            ps = conn.prepareStatement(sql);

            ps.setString(1, newCategory);
            ps.setLong(2, id);
            ps.setString(3, user.getUserName());

            rowsAffected = ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
            throw  new RuntimeException(e);
        }finally {
            DbUtil.close(rs,ps,conn);
        }
        return rowsAffected;

    }

    //查看全部笔记  创建时间和修改时间查看的时候才插入？
    public List<Note> selectAllNotes() throws Exception{
        List<Note> notesList = new ArrayList<>();

        try{
            conn= DbUtil.getConnection();
            String sql="SELECT notes.*, user.is_admin FROM notes JOIN user ON notes.user_nickname = user.user_nickname ";
            ps = conn.prepareStatement(sql);
            rs=  ps.executeQuery();
            while (rs.next()) {
                Long id = rs.getLong("id");
                String title = rs.getString("title");
                String content = rs.getString("content");
                //种类
                String category=rs.getString("category");
                Category category1 = Category.valueOf(category.toUpperCase());
                //名称
                //时间？先不要吧
                String username = rs.getString("user_nickname");
                String is_admin =rs.getString("is_admin");
                Note note=new Note();
                User user=new User();
                user.setUserName(username);
                user.setIsadmin(is_admin);
                note.setId(id);
                note.setTitle(title);
                note.setContent(content);
                note.setCategory(category1);
                note.setAuthor(user);

                notesList.add(note);
            }

        }
        finally {

            DbUtil.close(rs,ps,conn);
        }
        return notesList;
    }



    //查看分类笔记
    public List<Note> selectTypeNotes(String categoryName) throws Exception{
        List<Note> notesList = new ArrayList<>();
        try{
            conn= DbUtil.getConnection();
            String sql="SELECT notes.*, user.is_admin FROM notes JOIN user ON notes.user_nickname = user.user_nickname where category=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,categoryName);
            rs=  ps.executeQuery();
            while (rs.next()) {
                Long id = rs.getLong("id");
                String title = rs.getString("title");
                String content = rs.getString("content");
                //种类
                //名称
                //时间？先不要吧
                String username = rs.getString("user_nickname");
                String is_admin =rs.getString("is_admin");
                Note note=new Note();
                User user=new User();
                user.setUserName(username);
                user.setIsadmin(is_admin);
                note.setId(id);
                note.setTitle(title);
                note.setContent(content);
                Category category=Category.valueOf(categoryName.toUpperCase());
                note.setCategory(category);
                note.setAuthor(user);

                notesList.add(note);
            }

        }
        finally {

            DbUtil.close(rs,ps,conn);
        }
        return notesList;
    }





    //查看个人笔记
    public List<Note> selectPersonalNote(User user) throws Exception{

        List<Note> notesList = new ArrayList<>();
        try{
            conn= DbUtil.getConnection();
            String sql="select  *from notes where user_nickname=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            rs=  ps.executeQuery();
            while (rs.next()) {
                Note note =new Note();
                Long id = rs.getLong("id");
                String title = rs.getString("title");
                String content = rs.getString("content");
                String category=rs.getString("category");
                Category category1 = Category.valueOf(category.toUpperCase());



                note.setId(id);
                note.setTitle(title);
                note.setContent(content);
                note.setCategory(category1);
                note.setAuthor(user);

                notesList.add(note);

            }

        }
        finally {

            DbUtil.close(rs,ps,conn);
        }
        return notesList;
    }


  //查看个人的某条笔记
    public Note selectPersonalNoteById(User user,Long id) throws Exception{
        Note note =new Note();
        try{
            conn= DbUtil.getConnection();
            String sql="select  *from notes where user_nickname=? and id=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ps.setLong(1, id);

//                Long id = rs.getLong("id");
                String title = rs.getString("title");
                String content = rs.getString("content");
                String category=rs.getString("category");
                Category category1 = Category.valueOf(category.toUpperCase());



                note.setId(id);
                note.setTitle(title);
                note.setContent(content);
                note.setCategory(category1);
                note.setAuthor(user);



        }
        finally {

            DbUtil.close(rs,ps,conn);
        }
        return note;
    }






    //搜索笔记

    public List<Note> searchNotesByTitle(String keyword) throws SQLException {
        List<Note> foundNotes = new ArrayList<>();
        try {
                conn=   DbUtil.getConnection();
                String sql="SELECT * FROM notes WHERE title LIKE ?";
                ps=conn.prepareStatement(sql);
            // 参数化查询，使用'%'作为通配符
                ps.setString(1, "%" + keyword + "%"); // 注意这里的keyword应当先做好SQL注入防护

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Note note = new Note();
                    note.setId(rs.getLong("id"));
                    note.setTitle(rs.getString("title"));
                    note.setContent(rs.getString("content"));
                    User user=new User();
                    user.setUserName(rs.getString("user_nickname"));

                    note.setAuthor(user);
                    String categoryName=rs.getString("category");
                    note.setCategory(Category.valueOf(categoryName));

                    foundNotes.add(note);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

        return foundNotes;
    }

}
